package arithmetic.d_linklist;

import static utils.ListNodeUtils.createLink;
import static utils.ListNodeUtils.printLink;

import org.junit.jupiter.api.Test;

import utils.ListNodeUtils.ListNode;


/**
 * https://leetcode.cn/problems/add-two-numbers/
 *
 * @author jiangfeng on 2022/6/3
 */
public class AddTowNum {

    @Test
    public void test() {
        ListNode l1 = createLink(new int[] {2, 4, 9});
        ListNode l2 = createLink(new int[] {5, 6, 4,9});

        printLink(addTwoNumbers(l1, l2));
    }

    public static void reverse1(ListNode head) {
        // 防止影响原链表
        ListNode curr = head,next = null,pre = null;
        while (curr.next != null) {
            next = curr.next;
            curr.next = pre;
            pre=curr;
            curr = next;
        }
    }




    
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 1. 将两个链表反向
        l1 =  revese(l1);
        printLink(l1);
        l2 =  revese(l2);
        printLink(l2);

        // 2.开始正常计算
        ListNode result = null,dummyHead =new ListNode(),pre = dummyHead;
        int hasTen = 0;
        int val1 = 0,val2 = 0;;
        while(l1!=null || l2 != null ||hasTen!=0 ){
            val1 = 0;
            val2 = 0;
            if(l1!=null){
                val1 = l1.val;
                l1 = l1.next;
            }
            if(l2!=null){
                val2 = l2.val;
                l2 = l2.next;
            }
            int val = val1 + val2 + hasTen ;
            hasTen = val <  10? 0 : 1;
            result  = new ListNode(val%10);
            pre.next = result;
            pre = result;
        }
        return dummyHead.next;

    }

    public ListNode revese (ListNode h){
        ListNode next =null,pre = null;
        while(h!=null){
            next = h.next;
            h.next = pre;
            pre = h;
            h = next;
        }
        return pre;
    }

}
